<template>
  <div style="position:relative;height:100%;">
    <div :class="fullScreenStatus ? 'map-wrap-full' : 'map-wrap'">
      <div
        id="eden-map"
        :class="fullScreenStatus ? 'map-full' : ''"
      ></div>
    </div>
  </div>

</template>
<script>
import AMap from "AMap";
import DEVICE_PNG from "./icon/device.png";
import DEVICE_ALARM from "./icon/device_alarm_gif.gif";
import { getRealTimeBarList, cancelAlarm } from "@/api/operate";
import config from "@/config";
const socketUrl =
  process.env.NODE_ENV === "development"
    ? config.baseUrl.dev.substr(7, config.baseUrl.dev.length)
    : config.baseUrl.pro.substr(7, config.baseUrl.pro.length);
let vm = this;
export default {
  created() {
    vm = this;
  },
  mounted() {
    this.mapInit();
    this.getPoints();
    this.socketConn();
  },
  data() {
    return {
      points: [],
      map: "",
      fullScreenStatus: false,
      MarkerClustererMarker: "",
      vMarkerClustererMarkers: [],
      vMarkerClustererStatus: true,
      mysocket: null
    };
  },
  methods: {
    updateDatas(data) {
      this.$emit("sendData", data);
    },
    mapInit() {
      this.map = new AMap.Map("eden-map", {
        resizeEnable: true,
        center: [105, 34],
        zoom: 5,
        zooms: [3, 20],
        expandZoomRange: true,
        mapStyle: "amap://styles/fresh"
      });
    },
    markerClustererInit() {
      var points = this.points;
      if (points.length > 0) {
        const _this = this;
        for (let i = 0; i < points.length; i++) {
          let marker = new AMap.Marker({
            position: new AMap.LngLat(points[i].lng, points[i].lat),
            icon: points[i].isAlarm ? DEVICE_ALARM : DEVICE_PNG,
            offset: new AMap.Pixel(-15, -15),
            extData: i,
            map: _this.map
          });
          var infoWindow = new AMap.InfoWindow({
            isCustom: true,
            offset: new AMap.Pixel(20, -30)
          });
          marker.content = i;
          marker.on("click", markerClick);
          function markerClick(e) {
            //构建信息窗体中显示的内容
            var index = e.target.content;
            var device = points[index];

            //实例化信息窗体
            var title = device.installCode;
            var content = [];
            content.push(`<p ><span>sim卡号 :</span> ${device.sim}</p>`);
            content.push(
              `<p ><span>设备状态 :</span> ${
                device.devStatus ? "在线" : "离线"
              }</p>`
            );
            content.push(
              `<p ><span>是否报警 :</span> ${device.isAlarm ? "是" : "否"}</p>`
            );
            content.push(
              `<p ><span>位号编码 :</span> ${device.installCode}</p>`
            );
            content.push(`<p ><span>电池电量 :</span> ${device.battery}%</p>`);
            content.push(
              `<p ><span>信号强度 :</span> ${device.signalStrength}</p>`
            );
            content.push(`<p ><span>数据时间 :</span> ${device.dataTime}</p>`);
            if (device.isAlarm) {
              content.push(
                `<input type="button" class="map-btn" value="取消报警" onclick="cancelAlarm(${
                  device.sim
                })"/>`
              );
            }

            //构建自定义信息窗体
            function createInfoWindow(title, content) {
              var info = document.createElement("div");
              info.className = "custom-info input-card content-window-card";

              //可以通过下面的方式修改自定义窗体的宽高
              //info.style.width = "400px";
              // 定义顶部标题
              var top = document.createElement("div");
              var titleD = document.createElement("div");
              var closeX = document.createElement("img");
              top.className = "info-top";
              titleD.innerHTML = title;
              closeX.src = "https://webapi.amap.com/images/close2.gif";
              closeX.onclick = closeInfoWindow;

              top.appendChild(titleD);
              top.appendChild(closeX);
              info.appendChild(top);

              // 定义中部内容
              var middle = document.createElement("div");
              middle.className = "info-middle";
              middle.style.backgroundColor = "white";
              middle.innerHTML = content;
              info.appendChild(middle);

              // 定义底部内容
              var bottom = document.createElement("div");
              bottom.className = "info-bottom";
              bottom.style.position = "relative";
              bottom.style.top = "0px";
              bottom.style.margin = "0 auto";
              var sharp = document.createElement("img");
              sharp.src = "https://webapi.amap.com/images/sharp.png";
              bottom.appendChild(sharp);
              info.appendChild(bottom);
              return info;
            }

            //关闭信息窗体
            function closeInfoWindow() {
              _this.map.clearInfoWindow();
            }

            infoWindow.setContent(createInfoWindow(title, content.join("")));
            infoWindow.open(_this.map, e.target.getPosition());
          }
          _this.vMarkerClustererMarkers.push(marker);
        }
        // AMap.plugin(["AMap.MarkerClusterer"]);
        // AMap.plugin(["AMap.ToolBar", "AMap.MouseTool", "AMap.MarkerClusterer"]);
        AMap.plugin(
          ["AMap.ToolBar", "AMap.Scale", "AMap.OverView", "AMap.MapType"],
          function() {
            // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
            _this.map.addControl(new AMap.ToolBar());

            // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
            _this.map.addControl(new AMap.Scale());

            // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
            _this.map.addControl(new AMap.OverView({ isOpen: true }));

            // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
            _this.map.addControl(new AMap.MapType());
          }
        );
        _this.map.setFitView();
      }
    },
    async getPoints() {
      let res = await getRealTimeBarList({});
      if (res.code == 0) {
        console.log(res);
        this.points = res.data;
        this.markerClustererInit();
      }
    },
    fullScreen() {
      this.fullScreenStatus = !this.fullScreenStatus;
    },
    locateMarker(lng, lat) {
      this.map.setZoomAndCenter(17, [lng, lat]);
    },
    async cancelAlarm(sim) {
      let result = await cancelAlarm({ sim: sim });
      if (result.code == 0) {
        var index = null;
        for (let i = 0; i < this.points.length; i++) {
          if (this.points[i].sim == sim) {
            index = i;
            this.points[i].isAlarm = false;
            break;
          }
        }
        if (index != null) {
          this.map.getAllOverlays("marker").forEach(marker => {
            if (marker.getExtData() == index) {
              marker.setIcon(DEVICE_PNG);
              this.$emit("updateAlarmCount", -1);
            }
          });
          this.map.clearInfoWindow();
        }
      }
    },
    socketConn() {
      let loginName = sessionStorage.getItem("loginName");

      this.mysocket = new WebSocket(
        "ws://" + socketUrl + "/websocket/" + loginName
      );
      //打开事件
      this.mysocket.onopen = () => {
        console.log("Socket 已打开");
      };
      //获得消息事件
      this.mysocket.onmessage = msg => {
        console.log(msg.data);
        var obj = JSON.parse(msg.data);
        if (obj.alarm == 1) {
          var index = null;
          for (let i = 0; i < this.points.length; i++) {
            if (this.points[i].sim == obj.sim) {
              this.points[i].isAlarm = true;
              index = i;
              break;
            }
          }
          if (index != null) {
            this.map.getAllOverlays("marker").forEach(marker => {
              if (marker.getExtData() == index) {
                marker.setIcon(DEVICE_ALARM);
                this.$emit("updateAlarmCount", 1);
              }
            });
            this.map.clearInfoWindow();
          }
        }
      };
      //关闭事件
      this.mysocket.onclose = () => {
        console.log("Socket已关闭");
      };
      //发生了错误事件
      this.mysocket.onerror = () => {
        console.log("Socket发生了错误");
      };
      this.$router.afterEach(() => {
        this.mysocket.close();
      });
    }
  }
};

window.cancelAlarm = function(sim) {
  vm.cancelAlarm(sim);
};
</script>
<style>
.map-wrap {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  z-index: 110;
}
.map-wrap-full {
  position: fixed;
  width: 100% !important;
  height: 100% !important;
  z-index: 110;
  top: 0;
  left: 0;
}
.map-full {
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
.map-wrap #eden-map {
  width: 100%;
  height: 100%;
}
.map-operator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 200px;
  height: 85px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
}
.map-operator > div {
  position: relative;
  width: 52px;
  height: 52px;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 50px;
  cursor: pointer;
}
.map-operator .drawing {
  background-image: url("icon/draw.png");
  color: #fe6579;
}
.map-operator .submit {
  background-image: url("icon/submit.png");
  color: #a9ea0a;
}
.map-operator .clear {
  background-image: url("icon/clear.png");
  color: #b8c5cd;
}

.map-operator > div > div {
  position: absolute;
  width: 52px;
  height: 22px;
  line-height: 22px;
  left: 0;
  bottom: -22px;
  font-size: 14px;
}
.marker {
  position: absolute;
  top: -20px;
  right: -118px;
  color: #fff;
  padding: 4px 10px;
  box-shadow: 1px 1px 1px rgba(10, 10, 10, 0.2);
  white-space: nowrap;
  font-size: 12px;
  font-family: "";
  background-color: #25a5f7;
  border-radius: 3px;
}
.content-window-card {
  position: relative;
  box-shadow: none;
  bottom: 0;
  left: 0;
  width: auto;
  padding: 0;
}

.content-window-card p {
  line-height: 20px;
}
.content-window-card p span {
  float: left;
  width: 58px;
  color: #a1a1a1;
}
.custom-info {
  border: solid 1px silver;
}

div.info-top {
  position: relative;
  background: none repeat scroll 0 0 #09baf0;
  border-bottom: 1px solid #ccc;
  border-radius: 5px 5px 0 0;
}

div.info-top div {
  width: 100%;
  text-align: center;
  display: inline-block;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
  line-height: 31px;
  padding: 0 10px;
}

div.info-top img {
  position: absolute;
  top: 10px;
  right: 10px;
  transition-duration: 0.25s;
}

div.info-top img:hover {
  box-shadow: 0px 0px 5px #000;
}

div.info-middle {
  font-size: 12px;
  padding: 10px 10px;
  line-height: 20px;
}

div.info-bottom {
  height: 0px;
  width: 100%;
  clear: both;
  text-align: center;
}

.map-btn:hover {
  text-decoration: none;
}
.map-btn:hover {
  color: #fff;
  background-color: #25a5f7;
  border-color: #25a5f7;
}
.map-btn {
  width: 120px;
  margin: 5px 25px;
}
.map-btn {
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  border: 1px solid transparent;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
    border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  background-color: transparent;
  background-image: none;
  color: #25a5f7;
  border-color: #25a5f7;
  padding: 0.25rem 0.5rem;
  line-height: 1.5;
  border-radius: 1rem;
  -webkit-appearance: button;
  cursor: pointer;
}
</style>
